
goog.provide('esn.FacebookManager');

goog.require('esn.FacebookApi');
goog.require('esn.model.StudentModel');
goog.require('goog.array');
goog.require('goog.object');
goog.require('goog.json');
goog.require('goog.string');


/**
 * @constructor
 */
esn.FacebookManager = function(appContext, students) {
  this.appContext_ = appContext;

  this.fbApi_ = new esn.FacebookApi();

  this.studentClient_ = this.appContext_.getService(
      esn.constants.ServiceId.STUDENT_CLIENT);

  this.students_ = students;
};

esn.FacebookManager.prototype.getProfile = function() {
  if (!this.appContext_.isDevMode()) {
    this.fbApi_.getProfile(goog.bind(this.getProfileResponse_, this));
  } else {
    // We're in development mode so don't store the user's profile.
    this.getProfileResponse_(null);
  }
};

esn.FacebookManager.prototype.getProfileResponse_ = function(userProfile) {
   if (userProfile) {
     this.studentClient_.saveFacebookProfile(userProfile);
   }
};

esn.FacebookManager.prototype.matchFriends = function(callback) {
  if (!this.appContext_.isDevMode()) {
    this.fbApi_.getFriendList(
        goog.bind(this.getFriendListResponse_, this, callback));
  } else {
    // We're in development mode so don't store the user's profile.
    this.getFriendListResponse_(callback, this.createFriendsForDev_(20));
  }
};

esn.FacebookManager.prototype.logout = function(opt_callback) {
  this.fbApi_.logout(opt_callback);
};

esn.FacebookManager.prototype.getFriendListResponse_ = function(callback,
    friends) {
  var friendMatches = [];
  if (friends) {
    this.friends_ = friends;
    var fb_name_map = this.createFacebookNameMap_(this.friends_);
    friendMatches = this.getFriendMatches_(fb_name_map);
    this.saveFacebookFriends_(friends, friendMatches);
  }
  callback(friendMatches);
};

esn.FacebookManager.prototype.saveFacebookFriends_ = function(fb_friends,
    fb_matches) {
  // Convert our list of friend matches (list of students) into a list of
  // student id/fb id pairs (we just need to store the mapping since we already
  // have the other data).
  fb_matches = goog.array.map(fb_matches, function(fb_match) {
    return {'student_id': fb_match.getId(), 'fb_id': fb_match.getFacebookId()};
  });
  this.studentClient_.saveFacebookFriends(fb_friends, fb_matches);
};

esn.FacebookManager.prototype.createFacebookNameMap_ = function(friends) {
  var fb_name_map = {};
  goog.array.forEach(this.friends_, function(friend) {
    var lastName = friend['last_name'].toLowerCase();
    if (goog.object.containsKey(fb_name_map, lastName)) {
      fb_name_map[lastName].push(friend);
    } else {
      fb_name_map[lastName] = [friend];
    }
  });
  return fb_name_map;
};

esn.FacebookManager.prototype.getFriendMatches_ = function(fb_name_map) {
  var friendMatches = [];
  goog.array.forEach(this.students_, function(student) {
    var friendMatch = this.getFriendMatch_(fb_name_map, student);
    if (friendMatch) {
      friendMatches.push(student);
      if (!student.getFacebookId()) {
        student.setFacebookId(friendMatch['id']);
      }
    }
  }, this);
  return friendMatches;
};

esn.FacebookManager.prototype.getFriendMatch_ = function(fb_name_map, student) {
  var studentLastName = student.getLastName().toLowerCase();
  if (goog.object.containsKey(fb_name_map, studentLastName)) {
    return goog.array.find(fb_name_map[studentLastName], function(
        friend) {
      return goog.string.caseInsensitiveStartsWith(friend['first_name'],
          student.getFirstName()[0]);
    });
  }
  return null;
};

esn.FacebookManager.prototype.createFriendsForDev_ = function(numFriends) {
  var friends = [];
  for (var i = 0 ; i < numFriends; i++) {
    var student = this.students_[i];
    var friend = {
      'id': String(i + 100),
      'name': student.getFullName(),
      'first_name': student.getFirstName(),
      'last_name': student.getLastName()
    };
    friends.push(friend);
  }
  return friends;
};
